package com.lcq.gulimall.product.service.impl;

import com.lcq.common.constant.ProductConstant;
import com.lcq.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.lcq.gulimall.product.dao.AttrGroupDao;
import com.lcq.gulimall.product.dao.CategoryDao;
import com.lcq.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lcq.gulimall.product.entity.AttrGroupEntity;
import com.lcq.gulimall.product.entity.ProductAttrValueEntity;
import com.lcq.gulimall.product.service.CategoryService;
import com.lcq.gulimall.product.service.ProductAttrValueService;
import com.lcq.gulimall.product.vo.AttrRespVo;
import com.lcq.gulimall.product.vo.AttrVo;
import com.lcq.gulimall.product.vo.AttrVoUtils;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcq.common.utils.PageUtils;
import com.lcq.common.utils.Query;

import com.lcq.gulimall.product.dao.AttrDao;
import com.lcq.gulimall.product.entity.AttrEntity;
import com.lcq.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrName(attr.getAttrName());
//        attrEntity.setAttrType(attr.getAttrType());
//        attrEntity.setSearchType(attr.getSearchType());
//        attrEntity.setCatelogId(attr.getCatelogId());
//        attrEntity.setEnable(attr.getEnable());
//        attrEntity.setIcon(attr.getIcon());
//        attrEntity.setShowDesc(attr.getShowDesc());
//        attrEntity.setValueSelect(attr.getValueSelect());
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        if(attrEntity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        List<AttrRespVo> list  = new ArrayList<>();
        if(catelogId!=null && catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if(!StringUtils.isNullOrEmpty(key)){
            wrapper.and((wrap)->{
                wrap.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if(!StringUtils.isNullOrEmpty(type)){
            wrapper.and((wrap)->{
                wrap.eq("attr_type","base".equalsIgnoreCase(type)?1:0);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);

        page.getRecords().stream().forEach((entity)->{
            AttrRespVo attrRespVo = new AttrRespVo();
            AttrVoUtils.convert(entity,attrRespVo);
            if(entity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode()){
                AttrAttrgroupRelationEntity attrRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",entity.getAttrId()));
                if(attrRelation!=null&&attrRelation.getAttrGroupId()!=null){
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrRelation.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
            attrRespVo.setCatelogName(categoryDao.selectById(entity.getCatelogId()).getName());
            list.add(attrRespVo);
        });

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrRespVo getDetail(Long attrId) {
        AttrEntity entity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrVoUtils.convert(entity,attrRespVo);
        AttrAttrgroupRelationEntity attrRelation = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",
                entity.getAttrId()));
        if(entity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode()){
            if(attrRelation!=null&&attrRelation.getAttrGroupId()!=null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrRelation.getAttrGroupId());
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }
        attrRespVo.setCatelogPath(categoryService.findCateLogPath(entity.getCatelogId()));
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        AttrAttrgroupRelationEntity attrRelation = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",
                attrEntity.getAttrId()));
        if(attrEntity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode() && attr.getAttrGroupId()!=null){
            if(attrRelation!=null){
                attrRelation.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationDao.updateById(attrRelation);
            }else {
                attrRelation = new AttrAttrgroupRelationEntity();
                attrRelation.setAttrGroupId(attr.getAttrGroupId());
                attrRelation.setAttrId(attr.getAttrId());
                attrAttrgroupRelationDao.insert(attrRelation);
            }
        }
    }

    @Override
    public List<ProductAttrValueEntity> listForSpu(Long spuId) {
        if (spuId==null || spuId==0){
            return null;
        }
        return productAttrValueService.getBaseMapper().selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
    }

    @Transactional
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> spuAttrs) {
        if(spuAttrs==null||spuAttrs.size()==0){
            return;
        }
        List<Long> attrIds = spuAttrs.stream().map(e->{
            e.setSpuId(spuId);
            return e.getAttrId();
        }).collect(Collectors.toList());

         List<ProductAttrValueEntity> entities =  productAttrValueService.getBaseMapper().selectList(
                new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId).and(q->{
                    q.in("attr_id",attrIds);
                }));

         if(entities!=null&&entities.size()>0){
             productAttrValueService.removeByIds(entities.stream().map(e->{
                 return e.getId();
             }).collect(Collectors.toList()));
         }

        productAttrValueService.saveBatch(spuAttrs);
    }

    @Override
    public String getNameById(Long attrId) {
        AttrEntity entity = this.getById(attrId);
        return entity!=null?entity.getAttrName():"";
    }
}